package com.cuitrip.business.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.LoadingButton;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rx.BaseSubscriber;
import com.lab.utils.Utils;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscriber;

public class CertEmailActivity extends CustomUiFragmentActivity {

    public static final String KEY_VALUE = "KEY_VALUE";
    boolean isEnterEmail;
    @Bind(R.id.editView)
    EditText editEmail;
    @Bind(R.id.emailButton)
    LoadingButton button;
    @Bind(R.id.resendView)
    TextView resendView;
    @Bind(R.id.tipView)
    TextView tipView;
    @Bind(R.id.emailHolder)
    TextView emailHolder;
    String email = "";
    Subscriber<TextViewTextChangeEvent> subscriber = new BaseSubscriber<TextViewTextChangeEvent>() {
        @Override
        public void onNext(TextViewTextChangeEvent event) {
            boolean enable;
            String value;
            if (event.text() == null) {
                value = null;
            } else {
                value = event.text().toString();
            }
            if (isEnterEmail) {
                enable = Utils.isEmail(value);
            } else {
                enable = !TextUtils.isEmpty(value);
            }
            button.setEnabled(enable);
        }
    };

    ApiProxy apiProxy;
    private IProxyCallback verifyCallBack = new ApiProxyCallBack<Object>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            button.hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            Intent intent = new Intent();
            intent.putExtra(ShowCertInfoFragment.RESULT_DATA, email);
            setResult(RESULT_OK, intent);
            finish();
            TrackUtil.trackScreenName("/user/verification/email/verified");
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            button.setText(R.string.operation_verify);
            emailHolder.setText(response.msg);
            emailHolder.setSelected(true);
            return super.onFaild(response);
        }
    };
    private IProxyCallback sendCallBack = new ApiProxyCallBack(){
        @Override
        public void doPreWork(CtApiResponse response) {
            button.hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            if (!isEnterEmail) {
                return false;
            }
            ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
            choiceDialog.setDialogTitle(getResources().getString(R.string.verification_code_check));
            choiceDialog.setCancelable(false);
            choiceDialog.setDialogMessage(getString(R.string.verification_code_check_mail));
            choiceDialog.setDialogSingleStyleSetting(getString(R.string.operation_ok_2), new ChoiceDialog.DialogStyleSingleCallback() {
              @Override
              public boolean onPositiveButtonClick() {
                  isEnterEmail = false;
                  rendView();
                  return false;
              }
          });
            showDialogFragment(choiceDialog);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            button.setText(R.string.verification_code_send);
            emailHolder.setText(response.msg);
            emailHolder.setSelected(true);
            return super.onFaild(response);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_cert_email);
        ButterKnife.bind(this);
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.SEND_VERIFY_EMAIL, sendCallBack)
                .addApiCallBack(ApiManager.VERIFY_EMAIL, verifyCallBack).build();
        RxTextView
                .textChangeEvents(editEmail)
                .subscribe(subscriber);
        isEnterEmail = true;
        rendView();
        String value=getIntent().getStringExtra(KEY_VALUE);
        CtUserInfo userInfo=LoginInstance.getInstance().getUserInfo();
        if (userInfo!=null && !userInfo.isEmailValidated()&&!TextUtils.isEmpty(value)){
            editEmail.setText(value);
        }
    }

    /**
     * 渲染视图
     */
    private void rendView() {
        if (isEnterEmail) {
            //第一个阶段输入邮箱
            tipView.setText(R.string.mail_verify_desc);
            emailHolder.setText(R.string.mail_address_desc);
            emailHolder.setSelected(false);
            editEmail.setHint(R.string.mail_address);
            editEmail.setText(email);
            editEmail.setSelection(email != null ? email.length() : 0);
            button.setText(R.string.verification_code_send);
            resendView.setVisibility(View.GONE);
        } else {
            //第二个阶段输入Vcode
            tipView.setText(getString(R.string.verification_code_send_feedback_suc, email));
            emailHolder.setText(R.string.verification_code_desc_1);
            emailHolder.setSelected(false);
            editEmail.setHint(R.string.verification_code);
            editEmail.setText("");
            button.setText(R.string.operation_verify);
            String nomail=getString(R.string.mail_not_receive);
            String resend =getString(R.string.operation_resend);
            SpannableString ss=new SpannableString(nomail+" "+resend);
            ss.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    resend();
                }
            },ss.length()-resend.length(),ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            ss.setSpan(new ForegroundColorSpan(ResourceUtil.getThemeColor()), ss.length() - resend.length(), ss.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            resendView.setText(ss);
            resendView.setClickable(true);
            resendView.setMovementMethod(new LinkMovementMethod());
            resendView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        subscriber.unsubscribe();
    }

    void resend() {
        //set emailHolder
        emailHolder.setText(isEnterEmail ? R.string.mail_address_desc : R.string.verification_code_desc_1);
        emailHolder.setSelected(false);
        //移除输入法
        Utils.hideSoftInputMethod(this);
        if (button.isLoading()) {
            return;
        }
        button.showLoading();
        UserBusiness.sendVerifyEmail(apiProxy, email);
    }

    public void verify(){
        //set emailHolder
        emailHolder.setText(R.string.verification_code_desc_1);
        emailHolder.setSelected(false);
        //移除输入法
        Utils.hideSoftInputMethod(this);
        if (button.isLoading()) {
            return;
        }
        button.showLoading();
        UserBusiness.verifyEmail(apiProxy, email, editEmail.getText().toString());
    }

    @OnClick(R.id.button)
    void onButtonClick() {
        if (!button.isEnabled()){
            return;
        }
        if (isEnterEmail) {
            email = editEmail.getText().toString();
            resend();
        } else {
            //第二个阶段输入Vcode
            verify();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            onTopbarLeftPress();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTopbarLeftPress() {
        if (isEnterEmail){
            //正在输入邮箱->退出
            finish();
        } else {
            //正在输入Vcode->推到上一步
            isEnterEmail=true;
            rendView();
        }
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.mail_verify);
        return config;
    }
}
